<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>编辑销售单信息</title>
	<#include "/common/vue_resource.ftl">
	<style>
		.layui-card-header{font-weight:bold;}
		.layui-table[lay-size="sm"] td{padding:5px;}
		.product-table, .product-table th{text-align:center;}
		.product-table .layui-input{height:28px;display:inline-block;}
		.product-table .layui-btn-sm{height:27px;line-height:27px;vertical-align:top;}
		.more-parent, .ui-operating{font-size:12px;text-align:center;}
		.item{background:#e2e2e2;font-size:12px;padding:5px;border-radius:10px;padding-left:10px;padding-right:0px;}
	</style>
</head>
<body style="background:#f2f2f2;">
<div id="app" v-cloak>
	<div style="padding:10px;">
		<form class="layui-form" @submit.prevent="submitForm()" method="post">
			<div class="layui-card">
				<div class="layui-card-header">表单信息
					<button type="button" class="layui-btn layui-btn-sm layui-btn-danger" @click="top.showNotice('sale_order_add')">使用技巧</button>
				</div>
				<div class="layui-card-body">
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">客户<span class="ui-request">*</span></label>
							<div class="layui-input-inline">
								<input type="text" v-model="record.customerName" placeholder="点击选择客户" @click="showCustomerDialog" class="layui-input" readonly style="cursor:pointer;"/>
							</div>
						</div>
						<div class="layui-inline">
							<label class="layui-form-label">销售日期<span class="ui-request">*</span></label>
							<div class="layui-input-inline">
								<input type="text" v-model="record.saleDate" id="saleDate" placeholder="点击选择日期" class="layui-input" readonly style="cursor:pointer;"/>
							</div>
						</div>
						<#--<div class="layui-inline">
							<label class="layui-form-label">总价</label>
							<div class="layui-input-inline">
								<input type="text" v-model="record.totalAmount" placeholder="自动计算总价" class="layui-input" readonly/>
							</div>
						</div>-->
						<#--<div class="layui-inline">
							<label class="layui-form-label">已收金额</label>
							<div class="layui-input-inline">
								<input type="text" v-model="record.payAmount" class="layui-input"/>
							</div>
						</div>-->
					</div>
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">订单备注</label>
							<div class="layui-input-inline">
								<input type="text" v-model="record.remark" placeholder="请输入备注" class="layui-input" style="width:515px;"/>
							</div>
						</div>
					</div>
					<#--end-->
				</div>
			</div>
			<div class="layui-card">
				<div class="layui-card-header">
					商品信息 <span style="color:#FF5722;font-weight:normal;font-size:12px;margin-left:20px;">{{warnMsg}}</span>
					<div style="display:inline-block;float:right;font-weight:normal;font-size:12px;">
						<#--<span class="item">选择商品可以重复：<input type="checkbox" v-model="multiSelectProduct" value="1" style="display:inline-block;vertical-align:middle;margin-right:10px;"/></span>-->
						<span class="item"><@auth code='purchaseOrder_column_price'>进货价显示：<input type="checkbox" v-model="showPrice" value="1" style="display:inline-block;vertical-align:middle;margin-right:10px;"/></@auth></span>
						售价类型：
						<select v-model="priceType" class="layui-input" style="display:inline-block;width:100px;height:32px;line-height:32px;vertical-align:middle;">
							<option value="salePrice">零售价</option>
							<option value="memberPrice">会员价</option>
							<option value="tradePrice">批发价</option>
						</select>
						<#--<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" @click="newLineProduct" style="vertical-align:baseline;">新行</button>-->
						<#--<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" @click="showMultiProductDialog" style="vertical-align:baseline;">多选商品</button>-->
					</div>
				</div>
				<div class="layui-card-body" style="padding:0px;">
					<table class="layui-table product-table" lay-even lay-skin1="nob" lay-size="sm" style="margin:0px;">
						<thead>
						<tr>
							<th style="width:20px;">#</th>
							<th style="width:170px;">商品编码</th>
							<th>商品名称</th>
							<th style="width:80px;">规格</th>
							<th style="width:40px;">单位</th>
							<th style="width:40px;">数量</th>
							<@auth code='saleOrder_column_price'><th style="width:50px;">售价</th></@auth>
							<@auth code='purchaseOrder_column_price'><th v-if="showPrice.length > 0" style="width:50px;">进货价</th></@auth>
							<th style="width:35px;">折扣</th>
							<@auth code='saleOrder_column_price'><th style="width:20px;">小计</th></@auth>
							<th style="width:150px;">备注</th>
							<th style="width:40px;">操作</th>
						</tr>
						</thead>
						<tbody>
						<tr v-for="(item, index) in products">
							<td>{{1 + index}}</td>
							<td>
								<input type="text" v-model="item.productCode" class="layui-input" style="width1:130px;cursor:pointer;" readonly <#--@click="showMultiProductDialog"--> @click="showProductDialog(index)" placeholder="搜索商品"/>
								<#--<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" @click="showProductDialog(index)">选择</button>-->
							</td>
							<td>{{item.productName}}</td>
							<td>{{item.productStandard}}</td>
							<td>{{item.productUnit}}</td>
							<td><input type="text" v-model="item.quantity" class="layui-input" :data-index="index" data-modal="quantity" @keyup="inputKeyup($event, index, 'quantity')"/></td>
							<@auth code='saleOrder_column_price'><td><input type="text" v-model="item.salePrice" class="layui-input" :data-index="index" data-modal="salePrice" @keyup="inputKeyup($event, index, 'salePrice')"/></td></@auth>
							<@auth code='purchaseOrder_column_price'><td v-if="showPrice.length > 0"><input type="text" v-model="item.price" class="layui-input" :data-index="index" data-modal="price" @keyup="inputKeyup($event, index, 'price')"/></td></@auth>
							<td><input type="text" v-model="item.discount" class="layui-input" :data-index="index" data-modal="discount" @keyup="inputKeyup($event, index, 'discount')"/></td>
							<@auth code='saleOrder_column_price'><td>{{item.saleAmount}}</td></@auth>
							<td><input type="text" v-model="item.remark" class="layui-input" :data-index="index" data-modal="remark" @keyup="inputKeyup($event, index, 'remark')"/></td>
							<td class="more-parent">
								<div class="ui-operating" @click="removeProduct(index)">删除</div>
							</td>
						</tr>
						<tr>
							<td>#</td>
							<td>合计</td>
							<td></td>
							<td></td>
							<td></td>
							<td>{{record.totalNum}}</td>
							<@auth code='saleOrder_column_price'><td></td></@auth>
							<@auth code='purchaseOrder_column_price'><td v-if="showPrice.length > 0"></td></@auth>
							<td></td>
							<@auth code='saleOrder_column_price'><td>{{record.totalAmount}}</td></@auth>
							<td></td>
							<td class="more-parent"></td>
						</tr>
						<tr>
							<td colspan="12">
								<button type="button" class="layui-btn layui-btn-danger layui-btn-sm1" @click="showMultiProductDialog">选择商品</button>
							</td>
						</tr>
						</tbody>
					</table>
				</div>
			</div>

			<div class="layui-form-item">
				<div class="layui-input-block">
					<#--<input type="button" @click="submitForm" value="临时保存" class="layui-btn layui-btn-normal" />-->
					<input type="button" @click="paySubmit" value="收款保存" class="layui-btn" />
					<input type="button" @click="settleSubmit" value="结清保存" class="layui-btn layui-btn-normal" />
					<#--<input type="button" @click="newLineProduct" value="新行" class="layui-btn layui-btn-normal" />-->
					<input type="button" @click="screenShot" value="商品截图" class="layui-btn layui-btn-normal" />
					<input type="button" v-if="record.id" @click="remove" value="删除" class="layui-btn layui-btn-danger" />
				</div>
			</div>
			<div style="color:#FF5722;font-weight:normal;font-size1:12px;line-height:30px;">
				说明：<br/>
				1 正常情况下，请点“结清保存”。如有欠款或者已收部分款项，请点“收款保存”，日后可在销售单管理里面收款<br/>
				<#--2 “临时保存”是指仅仅保存单据，不会对相关商品的库存进行扣减、该单据也不纳入相关报表的统计<br/>-->
				2 折扣：100表示不打折，95表示95折<br/>
				3 如果客户退货，请在销售单数量中输入负数
			</div>
		</form>
	</div>
</div>
<script>
	var app = new Vue({
		el: '#app',
		data: {
			showTypes: false,
			record: {
				id: '${params.id!}',
				customerId: '',
				customerName: '',
				saleDate: '${.now?string("yyyy-MM-dd")}',
				totalAmount: '0',
				remark: '',
				payAmount: '0',
				productsStr: '',
				submitType: '',
			},
			products: [],
			currentProductClickIndex: 0,
			warnMsg: '',
			priceType: 'salePrice',
			showPrice: [],
			multiSelectProduct: ["1"],
		},
		mounted: function () {
			this.init();
			this.loadData();
		},
		watch: {
			products: {
				handler: function (newVal, oldVal) {
					this.calculateTotalAmount();
				},
				deep: true
			}
		},
		methods: {
			init: function () {
				var that = this;
				laydate.render({
					elem: '#saleDate', type: 'date', done: function (value) {
						that.record.saleDate = value;
					}
				});

				if (!this.record.id) {
					this.newLineProduct();
				}
			},
			newLineProduct: function () {
				this.products.push({
					productId: '',
					warehouseId: '',
					productCode: '',
					productName: '',
					productStandard: '',
					quantity: '',
					price: 0,
					salePrice: '',
					saleAmount: 0,
					discount: 100,
					remark: ''
				});
			},
			removeProduct: function (index) {
				this.products.splice(index, 1);
			},
			calculateTotalAmount: function () {
				var totalAmount = 0, totalNum = 0, allSuccess = true;
				for (var i = 0; i < this.products.length; i++) {
					var item = this.products[i];
					if (isNaN(item.quantity)) {
						allSuccess = false;
						this.warnMsg = "第" + (i + 1) + "行【数量】不是一个合法的数字";
						continue;
					}
					if (isNaN(item.salePrice)) {
						allSuccess = false;
						this.warnMsg = "第" + (i + 1) + "行【售价】不是一个合法的数字";
						continue;
					}
					if (isNaN(item.discount)) {
						allSuccess = false;
						this.warnMsg = "第" + (i + 1) + "行【折扣】不是一个合法的数字";
						continue;
					}
					var amount = CalculateFloat.floatMul(item.quantity || 0, item.salePrice);
					amount = CalculateFloat.floatMul(amount, item.discount);
					amount = CalculateFloat.floatDiv(amount, 100);
					item.saleAmount = amount;
					totalAmount = CalculateFloat.floatAdd(totalAmount, amount);

					totalNum = CalculateFloat.floatAdd(totalNum, item.quantity || 0);
				}
				this.record.totalAmount = totalAmount;
				this.record.totalNum = totalNum;
				if (allSuccess) {
					this.warnMsg = "";
				}
			},
			loadData: function () {
				if (!'${params.id!}') {
					return;
				}
				var that = this;
				$.http.post('${params.contextPath}/web/saleOrder/query.json', {id: '${params.id!}'}).then(function (data) {
					if (!data.success) {
						$.message(data.message);
						return;
					}
					var item = data.data;
					for (var key in  that.record) {
						that.record[key] = item[key];
					}
					that.products = item.saleItemList || [];
					that.calculateTotalAmount();
				});
			},
			settleSubmit: function () {
				this.record.submitType = "settle";
				this.submitForm();
			},
			paySubmit: function () {
				this.record.submitType = "pay";
				this.submitForm();
			},
			submitForm: function () {
				var that = this;
				this.record.productsStr = JSON.stringify(this.products);
				$.http.post('${params.contextPath}/web/saleOrder/<#if (params.id)??>modify<#else>save</#if>.json', this.record).then(function (data) {
					if (!data.success) {
						$.message(data.message);
						return;
					}

					var submitType = that.record.submitType || "";
					if ("pay" == submitType) {
						parent.app.income2(data.data);
						return;
					}
					var alt = layer.alert(data.message || "操作成功", function () {
						parent.app.loadData();
						parent.layer.closeAll();
						layer.close(alt);
					});
				});
			},
			showCustomerDialog: function () {
				var url = "${params.contextPath!}/view/business/customer/customer_dialog.htm";
				DialogManager.open({url: url, width: '90%', height: '100%', title: '选择客户'});
			},
			customerSelectCallBack: function (row) {
				this.record.customerId = row.id;
				this.record.customerName = row.name;
				DialogManager.closeAll();
			},
			showProductDialog: function (index) {
				this.currentProductClickIndex = index;
				var url = "${params.contextPath!}/view/business/product/product_stock_dialog.htm";
				DialogManager.open({url: url, width: '90%', height: '100%', title: '选择商品'});
			},
			productSelectCallBack: function (row) {
				if (this.multiSelectProduct.length <= 0) {
					for (var i = 0; i < this.products.length; i ++) {
						var item = this.products[i];
						if (item.productId == row.productId) {
							DialogManager.closeAll();
							return;
						}
					}
				}

				var product = this.products[this.currentProductClickIndex];
				product.productId = row.productId;
				product.warehouseId = row.warehouseId;
				product.productCode = row.productCode;
				product.productName = row.productName;
				product.productStandard = row.productStandard;
				product.productUnit = row.productUnit;
				product.price = row.buyPrice;
				product.salePrice = row[this.priceType] || '';
				if (this.currentProductClickIndex == (this.products.length - 1)) {
					this.newLineProduct();
				}
				DialogManager.closeAll();
			},
			showMultiProductDialog: function (index) {
				this.currentProductClickIndex = index;
				var url = "${params.contextPath!}/view/business/product/product_stock_dialog.htm?multi=1";
				DialogManager.open({url: url, width: '90%', height: '100%', title: '选择商品'});
			},
			multiProductSelectCallBack: function (row) {
				if (this.multiSelectProduct.length <= 0) {
					for (var i = 0; i < this.products.length; i++) {
						var item = this.products[i];
						if (item.productId == row.productId) {
							return;
						}
					}
				}
				var product = {quantity: '', saleAmount: '', discount: 100, remark: ''};
				product.productId = row.productId;
				product.warehouseId = row.warehouseId;
				product.productCode = row.productCode;
				product.productName = row.productName;
				product.productStandard = row.productStandard;
				product.productUnit = row.productUnit;
				product.price = row.buyPrice;
				product.salePrice = row[this.priceType] || '';
				this.products.push(product);

				for (var i = 0; i < this.products.length; i ++) {
					var item = this.products[i];
					if (item.productId) {
						continue;
					}
					this.products.splice(i, 1);
				}
				this.newLineProduct();
			},
			screenShot:function () {
				window.pageYoffset = 0;
				document.documentElement.scrollTop = 0;
				document.body.scrollTop = 0;
				html2canvas($(".product-table")[0]/*, {scale: 1}*/).then(function (canvas) {
					var type = "jpg";
					var imgData = canvas.toDataURL(type);
					var _fixType = function (type) {
						type = type.toLowerCase().replace(/jpg/i, 'jpeg');
						var r = type.match(/png|jpeg|bmp|gif/)[0];
						return 'image/' + r;
					};
					imgData = imgData.replace(_fixType(type), 'image/octet-stream');

					var saveFile = function (data, filename) {
						var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
						save_link.href = data;
						save_link.download = filename;
						var event = document.createEvent('MouseEvents');
						event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
						save_link.dispatchEvent(event);
					};

					//下载后的问题名
					var filename = '销售单-screenshot.' + type;
					saveFile(imgData, filename);
				});
			},
			remove:function () {//删除
				if (!confirm("确定删除订单吗?")) {
					return;
				}
				$.http.post("${params.contextPath}/web/saleOrder/delete.json", {ids: this.record.id || ""}).then(function (data) {
					if (!data.success) {
						$.message(data.message);
						return;
					}
					var alt = layer.alert(data.message || "操作成功", function () {
						parent.app.loadData();
						parent.layer.closeAll();
						layer.close(alt);
					});
				});
			},
			inputKeyup:function (e, index, modalName) {
				var modal = {'quantity': 0, 'salePrice': 1, 'price': 2, 'discount': 3, 'remark': 4};
				var modals = ['quantity', 'salePrice', 'price', "discount", "remark"];
				var keyCode = e.keyCode;
				if (keyCode == 37) {//左键
					var leftIndex = modal[modalName] - 1;
					leftIndex = leftIndex < 0 ? 0 : leftIndex;
					if (leftIndex == 2 && this.showPrice.length <= 0) {
						leftIndex = 1;
					}
					var leftName = modals[leftIndex];
					$("[data-index='" + index + "'][data-modal='" + leftName + "']").focus();
					return;
				}

				if (keyCode == 39) {//右键
					var rightIndex = modal[modalName] + 1;
					rightIndex = rightIndex > 4 ? 4 : rightIndex;
					if (rightIndex == 2 && this.showPrice.length <= 0) {
						rightIndex = 3;
					}
					var rightName = modals[rightIndex];
					$("[data-index='" + index + "'][data-modal='" + rightName + "']").focus();
					return;
				}

				if (keyCode == 40 || keyCode == 13) {//下键
					var nextIndex = index + 1;
					nextIndex = nextIndex > this.products.length - 1 ? this.products.length - 1 : nextIndex;
					$("[data-index='" + nextIndex + "'][data-modal='" + modalName + "']").focus();
					return;
				}

				if (keyCode == 38) {//上键
					var upIndex = index - 1;
					upIndex = upIndex < 0 ? 0 : upIndex;
					$("[data-index='" + upIndex + "'][data-modal='" + modalName + "']").focus();
					return;
				}
			},
		}
	});
</script>
</body>

</html>
